import config from '@/config/config.js';
import MD5 from 'js-md5';

const request = (option) => {
	return new Promise((resolve, reject) => {
		const {
			appId,
			appKey
		} = config;

		const timestamp = new Date().getTime();
		const param = `ApiRequest{appId=${appId},appKey=${appKey},timeStamp=${timestamp}}`;
		const tokenStr = MD5(param);
		console.log("timestamp----->", timestamp)
		console.log("tokenStr----->", tokenStr)

		// 构建请求的 URL
		const fullUrl = `${config.apiBaseUrl}${option.url}?appId=${appId}&timeStamp=${timestamp}&token=${tokenStr}`;
		console.log("所有请求完整的URL--->", fullUrl)
		
		
		const fullUrl2 = `${config.apiBaseUrl}/file/api/upload?appId=${appId}&timeStamp=${timestamp}&token=${tokenStr}`;
		const fullUrl3 = `${config.apiBaseUrl}/file/api/download?appId=${appId}&timeStamp=${timestamp}&token=${tokenStr}`;
		const fullUrl4 = `${config.apiBaseUrl}/file/api/addUserRole?appId=${appId}&timeStamp=${timestamp}&token=${tokenStr}`;
		console.log("文件上传URL--->", fullUrl2)
		console.log("文件下载前置URL--->", fullUrl3)
		// 使用uni.setStorageSync将用户信息存储到本地(会话机制)
		uni.setStorageSync('upload', fullUrl2);
		uni.setStorageSync('download', fullUrl3);
		uni.setStorageSync('addUserRole', fullUrl4);
		
		// 设置默认请求头
		const defaultHeaders = {
			'Content-Type': 'application/json',
			// 'Content-Type': 'multipart/form-data',
			// 其他默认请求头...
		};

		uni.request({
			url: fullUrl,
			data: option.data || {},
			header: {
				...defaultHeaders,
				...option.header
			},
			method: option.method || 'GET',
			success: (res) => {
				if (res.data.code === 200) {
					resolve(res.data);
				} else if(res.data.code === 500) {
					let errInfo = res.data?.msg || '未知错误';
					uni.showToast({
						icon: 'none',
						title: errInfo,
						duration: 3000
					});
					reject(new Error(`Error ${res.statusCode}:${errInfo}`));
				}
				else {
					let errInfo = res.data?.message || '未知错误';
					uni.showToast({
						icon: 'none',
						title: errInfo,
						duration: 3000
					});
					reject(new Error(`Error ${res.statusCode}:${errInfo}`));
				}
			},
			fail: (err) => {
				let errorInfo = '';
				if (err.errMsg.includes('timeout')) {
					errorInfo = '请求超时，请稍后重试';
				} else if (err.errMsg.includes('abort')) {
					errorInfo = '请求数据错误，请稍后重试';
				} else {
					errorInfo = '网络请求错误';
				}
				uni.showToast({
					title: errorInfo,
					duration: 5000,
					icon: "none"
				});
				reject(new Error(errorInfo));
			}
		});
	});
};

export default request;
